<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\OrderTemporary;
use app\common\model\ProductCart as CartModel;
use app\common\tool\Result;
use think\Response;

class Cart extends Base
{
    /** 
     * 购物车
     * */
    public function index()
    {
        try {
            $map = ['uid' => $this->user->id];
            $list = CartModel::getList($map, false, 'create_time', ['product']);
            foreach ($list as &$value) {
                $value['product']['spec_data'] = $value['product']['spec'] ? json_decode($value['product']['spec'], true) : [];
            }
            return Result::success('获取成功！', $list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 添加购物车商品
     */
    public function add(): Response
    {
        try {
            $param = $this->request->post();
            if (!$param['num'] || $param['num'] <= 0) {
                return Result::fail('数量错误');
            }
            return Result::fastReturn(CartModel::add($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 购物车操作
     */
    public function edit(): Response
    {
        try {
            return Result::fastReturn(CartModel::edit($this->request->post(), $this->user->id));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 购物车结算
     */
    public function submit(): Response
    {
        try {
            $param = $this->request->post();
            $param['type'] = 2;
            return Result::fastReturn(OrderTemporary::setTemporary($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
